// eslint-disable-next-line no-unused-vars
import { login, logout, getInfo, authenticate } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import store from '../index'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, code: code }).then(response => {
        if (response) {
          // const { token, userInfo } = response
          // window.sessionStorage.setItem('user', JSON.stringify(userInfo))
          const { object } = response
          window.sessionStorage.setItem('user', JSON.stringify(object))
          const token = 'token'
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    const user = JSON.parse(window.sessionStorage.getItem('user'))
    commit('SET_NAME', user.name)
    commit('SET_AVATAR', user.userface)
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        store.dispatch('permission/resetRoutes')
        store.dispatch('tagsView/delAllViews')
        window.localStorage.clear()
        window.sessionStorage.clear()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  updateName({ commit }, name) {
    commit('SET_NAME', name)
  },

  updateAvatar({ commit }, avatar) {
    commit('SET_AVATAR', avatar)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

